package com.example.demo.model.custom;

import com.baidu.bas.annotation.fun.DataProxy;
import com.baidu.bas.annotation.model.English;
import com.baidu.bas.core.util.ReflectUtil;
import com.baidu.bas.core.view.EruptModel;
import com.example.demo.model.Channel;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Map;

/**
 * @author liuzhenchuan@foxmail.com
 * @date 2020/12/29
 */
@Component
@Slf4j
public class ChannelDataProxy implements DataProxy<Channel> {

    @Resource
    private HttpServletRequest request;

    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        val language = request.getHeader("Accept-Language");
        if(language!=null && !language.contains("zh")){
            log.info("begin to convert english data ...");
            convertToEnglish(list);
        }
    }

    private void convertToEnglish(Collection<Map<String, Object>> list) {
        val field = ReflectUtil.findAllField(Channel.class).stream().filter(it->it.getAnnotation(English.class)!=null).findFirst().orElseGet(()->null);
        if(field!=null){
            val fieldName = field.getName();
            val anno =  field.getAnnotation(English.class);
            list.forEach(data->{
                val ename = data.get(fieldName);
                log.info("ename {}",ename);
                if(ename!=null){
                    data.put(anno.replace(),ename);
                }else{
                    data.put(anno.replace(),anno.defaultValue());
                }
            });
        }
    }

}
